<?php

/**
 * MembershipFeeBatchPaymentForm
 * 
 * @author Maximilian Lenkeit <dev@lenki.com>
 */
class MembershipFeeBatchPaymentForm extends sfForm
{
  
  /**
   * @var Doctrine_Collection
   */
  protected $members;
  protected $year;
  const NAME_FORMAT = 'membership_fee_batch_payment[%s]';

  function __construct (Doctrine_Collection $members = null, $year = null)
  {
    $this->members = $members;
    $this->year = $year;
    parent::__construct();
  }

  public function configure ()
  {
    foreach ($this->members as $member)
    {
      $this->addForm($member);
    }
    $this->disableLocalCSRFProtection();
    
    $this->mergePostValidator(new EmbeddedMembershipFeePaymentValidatorSchema());
    $this->widgetSchema->setNameFormat('membership_fee_batch_payment[%s]');
    
    parent::configure();
  }

  public function addForm (Member $member)
  {
    $payment = $member->getMembershipFeePaymentForYear($this->year);
    if (is_null($payment))
    {
      $payment = new MembershipFeePayment();
      $payment->setYear($this->year);
      $payment->setMemberId($member->getId());
    }
    $form = new EmbeddedMembershipFeePaymentForm($payment, array('member' => $member));
    $form->getWidgetSchema()->setNameFormat(sprintf(MembershipFeeBatchPaymentForm::NAME_FORMAT, $member->getId()) . '[%s]');
    $this->embedForm($member->getId(), $form);
  }

  /**
   * @return array
   */
  public function getMembershipFeePaymentForms ()
  {
    return $this->getEmbeddedForms();
  }

  public function bind (array $taintedValues = null, array $taintedFiles = null)
  {
    parent::bind($taintedValues, $taintedFiles);
    
    $embedded_forms = $this->getEmbeddedForms();
    
    foreach ($embedded_forms as $key => $embedded_form)
    {
      if (isset($taintedValues[$key]) && $embedded_form instanceof EmbeddedMembershipFeePaymentForm)
      {
        $embedded_form->bind($taintedValues[$key], array());
      }
    }
  }
}